import { autocompletion, CompletionContext, Completion, CompletionResult } from '@codemirror/autocomplete'
import { hoverTooltip, Tooltip } from "@codemirror/view"
import jsRuntime from './js-runtime.json'
import dogRuntim from './dog-runtime.json'

const completionsData = [...jsRuntime, ...dogRuntim, ...syncGMDoc(dogRuntim)]

// 所有 Completion 项
const completionItems: Completion[] = completionsData.map(entry => ({
  label: entry.label,
  type: entry.type,
  info: entry.info
}))

function syncGMDoc(dogDoc: CodeDocItem[]) {
  const docs: CodeDocItem[] = []
  for (const d of dogDoc) {
    const g = { ...d };
    g.label = g.label.replace('Dog', 'GM');
    docs.push(g);
    const gm_ = { ...d };
    if (g.label !== 'Dog') {
      gm_.label = gm_.label.replace('Dog.', 'GM_');
      docs.push(gm_);
    }
  }
  return docs
}

// 提取完整标识符（支持点运算符）
function getFullIdentifier(state: any, pos: number): { word: string; from: number; to: number } {
  const line = state.doc.lineAt(pos)
  const text = line.text
  let start = pos - line.from
  let end = start

  const isIdentChar = (ch: string) => /[\w$.]/i.test(ch)

  while (start > 0 && isIdentChar(text[start - 1])) start--
  while (end < text.length && isIdentChar(text[end])) end++

  const word = text.slice(start, end)
  return {
    word,
    from: line.from + start,
    to: line.from + end
  }
}

// 自动完成逻辑
function jsCompletionSource(context: CompletionContext): CompletionResult | null {
  const { word, from } = getFullIdentifier(context.state, context.pos)

  if (!word && !context.explicit) return null

  const options = completionItems.filter(item => item.label.startsWith(word))

  return {
    from,
    options
  }
}

// 构造 Map 方便查找
const infoMap = new Map(completionsData.map(item => [item.label, item.info]))
// 悬浮提示逻辑
const jsHoverTooltip = hoverTooltip((view, pos): Tooltip | null => {
  const { word, from, to } = getFullIdentifier(view.state, pos)
  const info = infoMap.get(word)
  if (!info) return null

  return {
    pos: from,
    end: to,
    above: true,
    create() {
      const dom = document.createElement("div")
      dom.textContent = info
      dom.style.padding = "4px 8px"
      dom.style.background = "#242424"
      dom.style.border = "1px solid #ccc"
      dom.style.borderRadius = "4px"
      dom.style.fontSize = "12px"
      return { dom }
    }
  }
})

// 导出整合扩展
export const jsHelperExtension = [
  autocompletion({ override: [jsCompletionSource] }),
  jsHoverTooltip
]